<template>
  <div class="home">
    <h2>App2 - Home Page</h2>
    
    <div class="info-section">
      <h3>从主应用接收的用户信息：</h3>
      <p>用户名：{{ userInfo?.name }}</p>
      <p>年龄：{{ userInfo?.age }}</p>
    </div>
    
    <div class="interaction-section">
      <h3>用户信息操作：</h3>
      <p>此页面展示了从主应用或其他子应用共享的数据</p>
      <div class="data-sync-status">
        <p v-if="lastUpdateTime">最后更新时间：{{ lastUpdateTime }}</p>
        <p>数据同步状态：{{ dataSynced ? '✅ 已同步' : '🔄 同步中...' }}</p>
      </div>
    </div>
    
    <div class="features">
      <h3>App2 功能展示：</h3>
      <ul>
        <li>📊 实时数据监控</li>
        <li>🔄 双向数据绑定</li>
        <li>🔗 应用间通信</li>
        <li>📱 响应式设计</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 用户信息
const userInfo = ref<any>(null)
const lastUpdateTime = ref('')
const dataSynced = ref(false)
let checkStateInterval: ReturnType<typeof setInterval> | null = null

// 获取全局状态
const getGlobalState = () => {
  const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
  if (globalState) {
    // 检查数据是否发生变化
    if (JSON.stringify(globalState.userInfo) !== JSON.stringify(userInfo.value)) {
      userInfo.value = { ...globalState.userInfo }
      updateLastSyncTime()
    }
    dataSynced.value = true
  }
}

// 更新最后同步时间
const updateLastSyncTime = () => {
  const now = new Date()
  lastUpdateTime.value = now.toLocaleTimeString()
}

onMounted(() => {
  // 获取初始状态
  getGlobalState()
  
  // 设置定时器检查状态变化
  checkStateInterval = setInterval(() => {
    getGlobalState()
  }, 500)
})

onUnmounted(() => {
  // 清理定时器
  if (checkStateInterval) {
    clearInterval(checkStateInterval)
  }
})
</script>

<style scoped>
.home {
  padding: 20px;
}

h2 {
  color: #2196f3;
  margin-bottom: 20px;
}

.info-section,
.interaction-section,
.features {
  background-color: #f8f8f8;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 8px;
}

h3 {
  margin-top: 0;
  color: #333;
}

.data-sync-status {
  background-color: #e8f5e8;
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
}

ul {
  margin-top: 10px;
  padding-left: 20px;
}

li {
  margin-bottom: 5px;
}
</style>